/*
 * 
 *  This file is part of Sourceprojects.org Lycia Copyright 2010 noctarius
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 */
package org.sourceprojects.lycia.internal.validation;

import java.math.BigDecimal;
import java.math.BigInteger;

import org.sourceprojects.lycia.ConstraintValidator;
import org.sourceprojects.lycia.annotations.Digits;

/**
 * 
 * @author noctarius
 * @since 1.9.1
 */
public class DigitsConstraintValidator implements ConstraintValidator<Digits> {
	private int integerDigits;
	private int fractionalDigits;

	@Override
	public void initialize(final Digits annotation) {
		integerDigits = annotation.integer();
		fractionalDigits = annotation.fraction();
	}

	@Override
	public boolean isValid(final Object object) {
		if (object == null) {
			return true;
		}

		String stringValue = null;

		if (object instanceof String) {
			try {
				stringValue = stringValue(new BigDecimal((String) object));
			} catch (final NumberFormatException nfe) {
				return false;
			}
		} else if (object instanceof BigDecimal) {
			stringValue = stringValue((BigDecimal) object);
		} else if (object instanceof BigInteger) {
			stringValue = stringValue((BigInteger) object);
		} else {
			return false;
		}

		final int pos = stringValue.indexOf(".");

		int left = (pos == -1) ? stringValue.length() : pos;
		final int right = (pos == -1) ? 0 : stringValue.length() - pos - 1;

		if (left == 1 && stringValue.charAt(0) == '0') {
			left--;
		}

		if (left > integerDigits || right > fractionalDigits) {
			return false;
		}

		return true;
	}

	private String stringValue(final BigDecimal number) {
		return number.abs().stripTrailingZeros().toPlainString();
	}

	private String stringValue(final BigInteger number) {
		return number.abs().toString();
	}

}
